// import fetch from 'dva/fetch';
// import {Toast} from 'antd-mobile';
//
// function parseJSON(response) {
//   return response.json();
// }
//
// function checkStatus(response) {
//   if (response.status >= 200 && response.status < 300) {
//     return response;
//   }
//
//   const error = new Error(response.statusText);
//   error.response = response;
//   throw error;
// }
//
// /**
//  * Requests a URL, returning a promise.
//  *
//  * @param  {string} url       The URL we want to request
//  * @param  {object} [options] The options we want to pass to "fetch"
//  * @return {object}           An object containing either "data" or "err"
//  */
// export default function request(url, options) {
//   return fetch(url, options)
//     .then(checkStatus)
//     .then(parseJSON)
//     .then(data => ({data}))
//     .catch(err => ({err}));
// }
//
// /*
// *   get 请求
// * */
// export function GET(url, option) {
//
// }


/* global window */
import axios from 'axios'
import cloneDeep from 'lodash.clonedeep'
import pathToRegexp from 'path-to-regexp'
import {Toast} from 'antd-mobile'


const fetch = (options) => {
  let {method = 'get', data, url} = options;
  const cloneData = cloneDeep(data);
  try {
    let domain = '';
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      [domain] = url.match(/[a-zA-z]+:\/\/[^/]*/);
      url = url.slice(domain.length);
    }
    const match = pathToRegexp.parse(url);
    url = pathToRegexp.compile(url)(data);
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domain + url
  }
  catch (e) {
    Toast.fail(e.message);
  }
  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
      });
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      });
    case 'post':
      return axios.post(url, cloneData);
    case 'put':
      return axios.put(url, cloneData);
    case 'patch':
      return axios.patch(url, cloneData);
    default:
      return axios(options)
  }
};

export default function request(options) {

  return fetch(options).then((response) => {
    const {statusText, status} = response;
    let data = response.data;
    if (data instanceof Array) {
      data = {
        list: data,
      }
    }
    return Promise.resolve({
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    })
  }).catch((error) => {
    const {response} = error;
    let msg;
    let statusCode;
    if (response && response instanceof Object) {
      const {data, statusText} = response;
      statusCode = response.status;
      msg = data.message || statusText;
    } else {
      statusCode = 600;
      msg = error.message || 'Network Error'
    }

    /* eslint-disable */
    return Promise.reject({success: false, statusCode, message: msg})
  })
}
